<template>
  <plain-page>
    <div class="container">
      <div style="width: 796px;" v-loading="loading">
        <el-card shadow="never" class="balance-card">
          <el-row :gutter="56">
            <el-col :span="4">
              <span class="balance-title">
                余额
              </span>
            </el-col>
            <el-col v-if="userOrgBalanceAccountShow"  :span="4">
              <span class="balance-title">
                预存款
              </span>
            </el-col>
            <el-col :span="4">
              <span class="balance-title">
                积分
              </span>
            </el-col>
            <el-col v-auth:integral_details :span="3" class="right-col">
              <el-button
                type="text"
                size="medium"
                icon="el-icon-tickets"
                @click="onIntegralDetailsClick">积分明细</el-button>
            </el-col>
            <el-col v-auth:trade :span="3" class="right-col">
              <el-button
                type="text"
                size="medium"
                icon="el-icon-tickets"
                @click="onTradeClick">交易流水</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="56" style="margin-top: 8px">
            <el-col :span="4">
              <animated-number
                :value="balances.balance"
                :precision="2"
                :animation-from-change-count="3"
                class="balance-num"
              />
            </el-col>
            <el-col v-if="userOrgBalanceAccountShow"  :span="4">
              <template v-if="userOrgBalanceAccount">
                <animated-number
                  :value="userOrgBalanceAccount.balance"
                  :precision="2"
                  :animation-from-change-count="hasUserOrgBalanceAccountOnLoad ? 2 : 1"
                  :difference-animation-from-change-count="hasUserOrgBalanceAccountOnLoad ? 2 : 1"
                  class="balance-num"
                />
              </template>
              <span v-else style="font-size: 13px">{{loading ? '-' : '未存过'}}</span>
            </el-col>
            <el-col :span="4">
              <animated-number :value="balances.points" :animation-from-change-count="3" class="balance-num secondary" />
            </el-col>
          </el-row>
        </el-card>

        <el-card v-if="currentAdmin.belongOrgId && $auth(['deposit', 'refund'])" shadow="never" style="margin-top: 4px;">
          <el-button v-auth:deposit type="warning" plain style="width: 60px" @click="onDepositClick">充值</el-button>
          <el-button v-auth:refund type="danger" plain style="width: 60px" :disabled="!userOrgBalanceAccount" @click="onRefundClick">退款</el-button>
        </el-card>

        <el-card v-if="userOrgBalanceAccounts.length" shadow="never" style="margin-top: 4px;">
          <data-table
            :data="userOrgBalanceAccounts"
            :showPagination="false"
            :height="171"
          >
            <el-table-column prop="belongOrgId" label="所属组织" width="100" />
            <el-table-column prop="balance" label="余额" width="100" v-slot="{row}">
              <span class="balance-num">{{row.balance}}</span>
            </el-table-column>
            <el-table-column prop="createAt" label="创建时间" width="154" />
            <el-table-column prop="balanceLastChangeAt" label="余额最后变动时间" />
          </data-table>
        </el-card>
        <el-card
          shadow="never"
          body-style="padding: 10px 20px;"
          style="margin-top: 4px; min-height: 424px;"
        >
          <el-tabs v-model="activeTab">
            <el-tab-pane name="coupon">
              <span slot="label">优惠券<span class="card-num">{{couponCount}}</span>张</span>
              <data-table
                ref="couponTable"
                url="/api/user/wallet/coupon/page"
                :queryParams="{providerId: '', scope: '', type: 0, accountId: $params.user.userType == 9 ? $params.user.deviceCode : $params.user.id}"
                :pagination="{pageSize: 10}"
                :height="300"
              >
                <el-table-column prop="couponNumber" label="编号" width="100" />
                <el-table-column prop="subject" label="主题" width="120" show-overflow-tooltip />
                <el-table-column prop="expiryTime" label="有效期" width="200" show-overflow-tooltip v-slot="{row}">
                  {{`${row.startTime.substring(0, 10)} ~ ${row.endTime.substring(0, 10)}`}}
                </el-table-column>
                <el-table-column prop="providerName" label="店铺" width="240" show-overflow-tooltip />
                <el-table-column prop="status" label="状态">
                  <template slot-scope="{row}">
                    <el-tag :type="['success', 'warning', 'info'][row.status]">
                      {{DictMan.itemMap('coupon.status')[row.status]}}
                    </el-tag>
                  </template>
                </el-table-column>
              </data-table>
            </el-tab-pane>
            <el-tab-pane name="serviceCard">
              <span slot="label">服务卡<span class="card-num">{{serviceCardCount}}</span>张</span>
              <data-table
                :data="serviceCards"
                :pagination="{pageSize: 10}"
                :height="300"
              >
                <el-table-column prop="cardNumber" label="卡号" width="120" show-overflow-tooltip />
                <el-table-column prop="cardName" label="名称" width="200" show-overflow-tooltip/>
                <el-table-column prop="price" label="价格" width="90" show-overflow-tooltip />
                <el-table-column prop="expiryTime" label="有效期" width="200" show-overflow-tooltip v-slot="{row}">
                  {{`${row.startTime.substring(0, 10)} ~ ${row.endTime.substring(0, 10)}`}}
                </el-table-column>
                <el-table-column prop="contactNumber" label="联系电话" show-overflow-tooltip />
              </data-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <old-card
        v-if="oldCardInfo.code != null"
        :card-info="oldCardInfo"
        :balance-value="balances.oldCardBlance"
        v-loading="loading"
        style="margin-left: 8px;"
      />
    </div>
    <deposit-dialog ref="depositDialog" />
    <refund-dialog ref="refundDialog" />
  </plain-page>
</template>

<script>
import AnimatedNumber from '@/components/AnimatedNumber';
import DepositDialog from './DepositDialog';
import RefundDialog from './RefundDialog';
import OldCard from './OldCard';

export default {
  pageProps: {
    title: '钱包'
  },
  components: {
    AnimatedNumber,
    DepositDialog,
    RefundDialog,
    OldCard
  },
  data() {
    return {
      permission: '/smart_info_center/life/user/user/finance/wallet',
      currentAdmin: app.admin,
      loading: true,
      activeTab: null,
      balances: {
        balance: null,
        oldCardBlance: null,
        points: null,
      },
      hasUserOrgBalanceAccountOnLoad: null,
      userOrgBalanceAccount: null,
      userOrgBalanceAccounts: [],
      couponCount: 0,
      serviceCardCount: 0,
      serviceCards: []
    };
  },
  computed: {
    userOrgBalanceAccountShow() {
      return app.admin.belongOrgId != null;
    },
    oldCardInfo() {
      return {code: this.$params.user.elderlyCard, ...this.$params.user};
    }
  },
  async mounted() {
    this.loading = true;
    this.balances.oldCardBlance = this.$params.user.elderlyCard ? 0 : null;
    this.loadUserOrgBalanceAccount(true);
    const ret = await this.$http.get('/api/user/wallet/get', {params: {userId: this.$params.user.id}});
    this.balances = {
      balance: +ret.gold,
      points: +ret.silver,
      oldCardBlance: null
    };
    this.balances.oldCardBlance = ret.oldCardBlance == '-1' ? 0 : ret.oldCardBlance;

    this.serviceCards = ret.cardList;

    this.couponCount = ret.couponList.length;
    this.serviceCardCount = ret.cardList.length;

    if (this.couponCount > 0) {
      this.activeTab = 'coupon';
    } else if (this.serviceCardCount > 0) {
      this.activeTab = 'serviceCard';
    }
    this.loading = false;
  },
  methods: {
    onDepositClick() {
      this.$refs.depositDialog.open({
        accountId: this.userOrgBalanceAccount && this.userOrgBalanceAccount.id,
        user: this.$params.user,
        onSuccess: () => {
          this.loadUserOrgBalanceAccount();
        }
      });
    },
    onRefundClick() {
      this.$refs.refundDialog.open({
        accountId: this.userOrgBalanceAccount.id,
        user: this.$params.user,
        onSuccess: () => {
          this.loadUserOrgBalanceAccount();
        }
      });
    },
    onTradeClick() {
      let { user } = this.$params;
      this.pushPage({
        path: '/shop/finance/trade',
        params: { query: {userAccount: user.id} },
        subTitle: user.realName || user.aliasName,
        key: user.id
      });
    },
    onIntegralDetailsClick() {
      let { user } = this.$params;
      this.openTab({
        url: "view/user/userIntegral/userIntegralDetailFom.do?accountId=" + user.id,
        title: (user.realName || user.aliasName) + " - 积分记录"
      });
    },
    loadUserOrgBalanceAccount(init) {
      if (app.admin.belongOrgId) {
        this.$http.get('/api/user/wallet/user-org-balance-account',
          {params: {userId: this.$params.user.id, belongOrgId: app.admin.belongOrgId}}).then(({data: account}) => {
            if (init) {
              this.hasUserOrgBalanceAccountOnLoad = !!account;
            }
            if (account) {
              this.userOrgBalanceAccount = account;
            }
          });
      } else if (app.admin.roleId == 1) {
        this.$http.get('/api/user/wallet/user-org-balance-account',
          {params: {userId: this.$params.user.id}}).then(({data: accounts}) => {
            this.userOrgBalanceAccounts = accounts;
          });
      }
    }
  },
}
</script>


<style scoped>
.container {
  display: flex;
  justify-content: center;
  min-width: 1220px;
}
.balance-card .el-button {
  padding: 0px;
}
.right-col {
  float: right;
  padding: 0px !important;
}

.balance-title {
  font-size: 14px;
  color: #909399;
}
.balance-num {
  font-size: 20px;
  font-weight: bold;
  color: #606266;
  line-height: 24px;
}
.balance-num.secondary {
  font-weight:normal;
  color: #606266;
}

.card-num {
  padding: 0px 4px;
}
</style>
